package com.koi.common.config;

import com.koi.common.utils.string.CutOutUtil;
import com.koi.common.xxs.XssAndSqlFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.HashMap;
import java.util.Map;

/**
 * @description [防止SQL注入、XSS攻击、CSRF/CROS恶意访问，需要guava包依赖]
 * @author ･ᴗ･
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${koi.filePath}")
    private String baseFilePath;

    // -excludes用于配置不需要参数过滤的请求url
    // -isIncludeRichText默认为true，主要用于设置富文本内容是否需要过滤
    @Bean
    public FilterRegistrationBean xssFilterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new XssAndSqlFilter());
        filterRegistrationBean.setOrder(1);
        filterRegistrationBean.setEnabled(true);
        filterRegistrationBean.addUrlPatterns("/*");
        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("excludes", "/favicon.ico, /img/*, /js/*, /css/*");
        initParameters.put("isIncludeRichText", "true");
        filterRegistrationBean.setInitParameters(initParameters);
        return filterRegistrationBean;
    }

    /**
     * @description [配置静态资源映射-本地图片回显-实现implements WebMvcConfigurer]
     * @author ･ᴗ･
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** SpringBoot 所需 favicon.ico 图标 */
        registry.addResourceHandler("favicon.ico").addResourceLocations("classpath:/static/");
        /** 本地文件上传路径 */
        registry.addResourceHandler(CutOutUtil.deleteCharacterBefore("/", baseFilePath) + "/**").addResourceLocations("file:" + baseFilePath + "/");
    }

}
